package com.sense.kukoo.biz_library.view

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.sense.kukoo.biz_library.R
import com.sense.kukoo.biz_library.adapter.SubscriptionsAdapter
import com.sense.kukoo.biz_library.databinding.BizLibraryFragmentSubscriptionsBinding
import com.sense.kukoo.biz_library.vm.SubscriptionsViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.bean.LibrarySubscriptionBean
import com.sense.kukoo.common.repo.bean.SubscriptionsBean
import com.sense.kukoo.common.wiget.state.PreloginSubscriptionsState
import com.zy.multistatepage.state.SuccessState

class SubscriptionsFragment : BaseMvvmFragment<SubscriptionsViewModel, BizLibraryFragmentSubscriptionsBinding>() {

    private val TAG: String = javaClass.simpleName
    private lateinit var mAdapter:SubscriptionsAdapter

    private var mCurrentMusic: LocalMediaListItemBean? = null
    private var mCurrentState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {}
    }

    override fun getLayout(): Int = R.layout.biz_library_fragment_subscriptions

    override fun getViewModelClass(): Class<SubscriptionsViewModel> = SubscriptionsViewModel::class.java

    companion object {
        @JvmStatic
        fun newInstance(arg_type: String) = SubscriptionsFragment().apply {}
    }

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindAction(mViewModel.action_toDetailPage){
            toDetailPage(it)
        }
        //
        mViewModel.mSubscriptionsData.observe(viewLifecycleOwner){
            //
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
            mAdapter.list = it
            mAdapter.notifyDataSetChanged()
        }
        mViewModel.enableLoadMore.observe(viewLifecycleOwner){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        val data = arrayListOf<SubscriptionsBean>()
        mAdapter = SubscriptionsAdapter(data, mListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            //mViewModel.refreshData()
            mBinding.refreshLayout.finishRefresh()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            //mViewModel.loadMoreData()
            mBinding.refreshLayout.finishLoadMore()
        }
    }

    override fun singleLazyLoad() {}

    override fun onResume() {
        super.onResume()
        refresh()
    }

    fun refresh(){
        if(Repo.login.isLogin()){
            multiState.show<SuccessState>()
            mBinding.refreshLayout.autoRefresh()
        } else {
            multiState.show<PreloginSubscriptionsState> {
                it.onSignIn {
                    ARouter.getInstance()
                        .build(ARouterUrl.ROUTE_ME_MODULE_LOGIN_ACTIVITY)
                        .navigation()
                }
            }
        }
    }

    private val mListener = object : SubscriptionsAdapter.SubscriptionsEventListener {
        override fun onChannelSeeAll(item: SubscriptionsBean) {
            ARouter.getInstance()
                        .build(ARouterUrl.ROUTE_LIBRARY_MODULE_MY_SUBSCRIPTIONS_ACTIVITY)
                        .navigation()
        }

        override fun onChannelItemClick(item: SubscriptionsBean, position: Int) {
            val channelItem: LibrarySubscriptionBean = item.channelItem!![position]
            if (channelItem.isShowRedDot()) {
                //消除红点
                mViewModel.onChannelItemClick(channelItem)
            }else{
                toDetailPage(channelItem)
            }
        }

        override fun onRecentlyUpdatedItemClick(item: SubscriptionsBean) {
            val recentItem = item.recentItem!!
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+recentItem.bookId)
                .navigation()
        }

        override fun onRecentlyUpdatedPlay(item: SubscriptionsBean) {
            val recentItem = item.recentItem!!
            //
            if(mCurrentMusic != null
                && mCurrentMusic?.idOfBooks() == recentItem.idOfBook()
                && mCurrentMusic?.idOfChapter() == recentItem.idOfChapter()){
                //当前音乐
                when (mCurrentState) {
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        //播放中
                        Kukoo.input.pause()
                    }
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                        Kukoo.input.start()
                    }
                    else -> {
                        //补全数据并播放
                        mViewModel.loadItemDataAndPlay(recentItem)
                    }
                }
            } else {
                //非当前
                //补全数据并播放
                mViewModel.loadItemDataAndPlay(recentItem)
            }
        }
    }

    private val mWatcher = object : UserWatcher.MusicStateWatcher {

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentState = state
            mAdapter.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        Kukoo.watcher.unregister(mWatcher)
    }

    private fun toDetailPage(channelItem: LibrarySubscriptionBean){
        ARouter.getInstance()
            .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
            .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+channelItem.book.id)
            .navigation()
    }
}